package org.zero.onlinesubject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.zero.onlinesubject.common.vo.ClassInfoVo;
import org.zero.onlinesubject.entity.ClassGroup;
import org.zero.onlinesubject.entity.ClassInfo;
import org.zero.onlinesubject.entity.GroupMember;
import org.zero.onlinesubject.entity.User;
import org.zero.onlinesubject.mapper.ClassGroupMapper;
import org.zero.onlinesubject.mapper.UserMapper;
import org.zero.onlinesubject.service.ClassInfoService;
import org.zero.onlinesubject.mapper.ClassInfoMapper;
import org.springframework.stereotype.Service;
import org.zero.onlinesubject.service.GroupMemberService;
import org.zero.onlinesubject.service.UserService;
import org.zero.onlinesubject.utils.IDWorker;
import org.zero.onlinesubject.utils.UserContextHolder;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class ClassInfoServiceImpl extends ServiceImpl<ClassInfoMapper, ClassInfo>
    implements ClassInfoService{

    @Resource
    private ClassInfoMapper classInfoMapper;

    @Resource
    private UserService userService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ClassGroupMapper classGroupMapper;

    @Resource
    private GroupMemberService groupMemberService;

    @Value("${file.external_path}")
    private String externalPath;

    @Override
    public List<ClassInfo> getClassList(String userId) {
        QueryWrapper<ClassInfo> wrapper = new QueryWrapper<>();
        wrapper.eq(!StringUtils.isNullOrEmpty(userId),"HeadTeacherID",userId);

        List<ClassInfo> list = classInfoMapper.selectList(wrapper);
        list.forEach(item->{
            item.setClassphoto(externalPath + item.getClassphoto());
        });
        return list;
    }

    @Transactional
    @Override
    public Boolean createClass(ClassInfo classInfo) {
        User user = UserContextHolder.get();
        if(user.getRoleid()!=3){
            throw new RuntimeException("只有老师可以创建班级");
        }
        classInfo.setHeadteacherid(user.getUserid());
        boolean flag = save(classInfo);
        // 创建班级群
        ClassGroup classGroup = new ClassGroup();
        String gid = IDWorker.createGID();
        classGroup.setGroupid(gid);
        classGroup.setClassid(classInfo.getClassid());
        classGroup.setGroupname(classInfo.getClassname());
        classGroup.setGroupavatar(classInfo.getClassphoto());
        classGroup.setCreaterid(classInfo.getHeadteacherid());
        classGroup.setCreatetime(LocalDateTime.now());
        int row = classGroupMapper.insert(classGroup);
        // 设置群成员身份
        GroupMember member = new GroupMember();
        member.setGroupid(gid);
        member.setMemberid(user.getUserid());
        member.setMembernote(user.getUsername());
        member.setMemberrole("0001");
        member.setMemberstatus("0001");
        member.setJointime(LocalDateTime.now());
        boolean flag2 = groupMemberService.save(member);

        return flag && row!=0 && flag2;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean joinClass(String classId, String userId) {
        User user = userMapper.selectById(userId);
        if(user.getClassid()!=null){
            return false;
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<User>();
        updateWrapper.eq("UserID",userId).set("ClassID",classId);
        boolean f1 = userMapper.update(updateWrapper) != 0;
        boolean f3 = false;
        if(f1){
            UpdateWrapper<ClassInfo> wrapper = new UpdateWrapper<>();
            wrapper.eq("ClassID",classId).setSql("ClassSize = ClassSize + 1");
            f3 = classInfoMapper.update(wrapper)!=0;
        }

        QueryWrapper<ClassGroup> wrapper = new QueryWrapper<>();
        wrapper.eq(!StringUtils.isNullOrEmpty(classId),"ClassID",classId).last(" limit 1");
        ClassGroup classGroup = classGroupMapper.selectOne(wrapper);

        GroupMember groupMember = new GroupMember();
        groupMember.setGroupid(classGroup.getGroupid());
        groupMember.setMembernote(user.getUsername());
        groupMember.setMemberid(user.getUserid());
        groupMember.setMemberrole("0003");
        groupMember.setMemberstatus("0001");
        groupMember.setJointime(LocalDateTime.now());
        boolean f2 = groupMemberService.save(groupMember);

        return f1 && f2 && f3;
    }

    @Override
    public boolean asignTeacherToClass(String userId, String[] classList) {
        int num = classInfoMapper.asignTeacherToClass(userId,classList);
        return num!=0;
    }

    @Override
    public List<ClassInfo> getClassByCond(String classname, Integer current, Integer size) {
        QueryWrapper<ClassInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isNullOrEmpty(classname)){
            wrapper.like("ClassName",classname);
        }
        wrapper.last(" limit "+current+","+size);

        List<ClassInfo> list = classInfoMapper.selectList(wrapper);
        list.forEach(item->{
            item.setClassphoto(externalPath + item.getClassphoto());
        });

        return list;
    }

    @Override
    public List<ClassInfo> getJoinClass(String userid) {
        List<ClassInfo> list = classInfoMapper.getJoinClass(userid);
        list.forEach(info->{
            info.setClassphoto(externalPath + info.getClassphoto());
        });
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCls(String classId) {
        Boolean f1 = removeById(classId);
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("ClassID",classId).set("ClassID",null);
        Boolean f2 = userService.update(wrapper);
        UpdateWrapper<ClassGroup> wrapper2 = new UpdateWrapper<>();
        wrapper.eq("ClassID",classId);
        Boolean f3 = classGroupMapper.delete(wrapper2)!=0;
        return f1 && f2 && f3;
    }
}
